import 'package:flutter/material.dart';
import 'package:silver_flutter/book_page.dart';
import 'package:silver_flutter/model/book.dart';
import 'package:silver_flutter/api.dart' as api;

class BookList extends StatefulWidget {
  final String fetchPath;

  BookList({Key key, this.fetchPath}) : super(key: key);

  @override
  _BookListState createState() => new _BookListState();
}

class _BookListState extends State<BookList> {
  @override
  Widget build(BuildContext context) {
    return new FutureBuilder<List<Book>>(
      future: api.fetchBooks(widget.fetchPath),
      builder: (context, snapshot) {
        if (snapshot.hasData) {
          return new GridView.count(
              primary: false,
              padding: const EdgeInsets.all(10.0),
              crossAxisSpacing: 10.0,
              crossAxisCount: 3,
              mainAxisSpacing: 10.0,
              childAspectRatio: 3.0 / 4.0,
              children: snapshot.data
                  .map((book) => new GestureDetector(
                        onTap: () {
                          Navigator.push(
                            context,
                            new MaterialPageRoute(
                                builder: (context) => new BookPage(
                                      book: book,
                                    )),
                          );
                        },
                        child: new Image.network(book.coverImageUrl,
                            fit: BoxFit.fill),
                      ))
                  .toList());
        } else if (snapshot.hasError) {
          return new Text("${snapshot.error}");
        }

        // By default, show a loading spinner
        return new Center(child: new CircularProgressIndicator());
      },
    );
  }
}
